package com.qr.controller;

import com.qr.constant.Constant;
import com.qr.dto.UserLoginDTO;
import com.qr.entity.User;
import com.qr.properties.JwtProperties;
import com.qr.result.Result;
import com.qr.service.UserService;
import com.qr.utils.JwtUtil;
import com.qr.vo.UserLoginVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.Map;

@RestController
@Slf4j
public class UserController {

    @Autowired
    private UserService userService;

    @Autowired
    private JwtProperties jwtProperties;

    @PostMapping("/login")
    public Result<UserLoginVO> login(@RequestBody UserLoginDTO userLogindto) {
        User user = userService.Login(userLogindto);

        // 生成token
        Map<String, Object> claims = new HashMap<>();
        claims.put(Constant.USER_ID, user.getId());
        String token = JwtUtil.createJWT(jwtProperties.getUserSecretKey(), jwtProperties.getUserTtl(), claims);

        UserLoginVO vo = UserLoginVO.builder()
                .id(user.getId())
                // .openid(user.getOpenid())
                .token(token)
                .build();

        return Result.success(vo, Constant.LOGIN_SUCCESS);
    }

    /**
     * 更新用户头像和姓名
     */
    @PostMapping("/setUserInfo")
    public Result<String> setUserInfo(@RequestBody User user) {
        log.info("更新用户信息：{}", user);
        userService.updateById(user);
        return Result.success(Constant.UPDATE_SUCCESS);
    }

    /**
     * 获取用户信息
     */
    @GetMapping("/getUserInfo")
    public Result<User> getUserInfo() {
        User user = userService.getById();
        return Result.success(user, Constant.QUERY_SUCCESS);
    }
}
